package com.moore.utils;

import com.alibaba.fastjson2.JSON;
import com.moore.model.Comment;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class CommentUtils {

    public static String insertComment(String goodsId, String nickname, String comment) {
        String sql = "insert into appraise (goods_id, nickname, content, time) values (?, ?, ?, ?)";
        int num;
        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String time = now.format(formatter);
            num = JDBCUtils.executeUpdate(sql, goodsId, nickname, comment, time);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (num >= 1){
            return "success";
        } else {
            return "fail";
        }
    }

    public static String getComment(String goodId) {
        String sql = "select * from appraise where goods_id = " + goodId;
        List<String> list;
        List<String> arrasyList = new ArrayList<>();
        try {
            list = JDBCUtils.executeSelect(sql,"id","goods_id","nickname","content","time");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        int i = 0;
        while (true) {
            if (5*i+4 > list.size()){
                break;
            }
            Comment comment = new Comment(
                    list.get(5 * i),
                    list.get(5 * i + 1),
                    list.get(5 * i + 2),
                    list.get(5 * i + 3),
                    list.get(5 * i + 4)
            );
            i++;
            arrasyList.add(JSON.toJSONString(comment));
        }
        return JSON.toJSONString(arrasyList);
    }
}
